package com.ruoyi.web.service.Impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.mes.MesMachinePaper;
import com.ruoyi.web.domain.mes.MesPaper;
import com.ruoyi.web.domain.vo.RefundDetailVo;
import com.ruoyi.web.mapper.MesConfigMapper;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.mapper.MesRefundInfoMapper;
import com.ruoyi.web.service.IMesRefundInfoService;

import javax.annotation.Resource;

/**
 * 退库单Service业务层处理
 * 
 * @author wxt
 * @date 2024-01-23
 */
@Service
public class MesRefundInfoServiceImpl implements IMesRefundInfoService 
{
    @Resource
    private MesRefundInfoMapper mesRefundInfoMapper;

    @Resource
    private MesPaperService mesPaperService;

    @Resource
    private MesConfigMapper configMapper;
    /**
     * 查询退库单
     * 
     * @param id 退库单主键
     * @return 退库单
     */
    @Override
    public MesRefundInfo selectMesRefundInfoById(Long id)
    {
        return mesRefundInfoMapper.selectMesRefundInfoById(id);
    }

    /**
     * 查询退库单列表
     * 
     * @param mesRefundInfo 退库单
     * @return 退库单
     */
    @Override
    public List<MesRefundInfo> selectMesRefundInfoList(MesRefundInfo mesRefundInfo)
    {
        return mesRefundInfoMapper.selectMesRefundInfoList(mesRefundInfo);
    }
    @Override
    public List<RefundDetailVo> selectMesDetaillist(MesRefundInfo mesRefundInfo)
    {
        List<RefundDetailVo> refundDetailVos = mesRefundInfoMapper.selectMesDetaillist(mesRefundInfo);
        BigDecimal decimal = mesRefundInfoMapper.selectMesDetaillistSumTotal(mesRefundInfo);
        if(refundDetailVos.size() > 0){
            refundDetailVos.get(0).setTotalSum(decimal);
        }
        return refundDetailVos;
    }



    /**
     * 新增退库单
     * 
     * @param mesRefundInfo 退库单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertMesRefundInfo(MesRefundInfo mesRefundInfo)
    {
        mesRefundInfo.setCreateTime(DateUtils.getNowDate());

        // 生成退库单编号
//        int maxNum = mesRefundInfoMapper.getRefundInfoMaxId();

        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "refund_num");
        map.put("tableName", "mes_refund_info");
        int maxNum = configMapper.getMaxId(map);

        String code = PinYinUtils.getCodeNormal(maxNum, "ZZTKD");
        mesRefundInfo.setRefundNum(code);

        int rows = mesRefundInfoMapper.insertMesRefundInfo(mesRefundInfo);
        insertMesRefundDetail(mesRefundInfo);
        return rows;
    }

    /**
     * 修改退库单
     * 
     * @param mesRefundInfo 退库单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesRefundInfo(MesRefundInfo mesRefundInfo)
    {
        int status=mesRefundInfo.getStatus();
        if (status==2)//提交
           {
               MesRefundInfo Info= mesRefundInfoMapper.selectMesRefundInfoById(mesRefundInfo.getId());//查询数据库
               List<MesRefundDetail> mesDetailList = Info.getMesRefundDetailList();

               if (mesDetailList.size()!=0) {
                   // 获取纸张ids
                   List<Long> listId = mesDetailList.stream().map(it -> it.getPaperid()).collect(Collectors.toList());
                   Long[] ids = listId.toArray(new Long[0]);
                   MesMachinePaper machinePaper = new MesMachinePaper();
                   machinePaper.setPaperids(ids);//纸张id
                   machinePaper.setMachineid(Info.getRefundMachineid());//机台id
                   // 根据纸张id和机台查询
                   List<MesMachinePaper> MPaper = mesPaperService.selectMachinePaperByIds(machinePaper);

                   if (MPaper.size() != 0) {
                       for (MesRefundDetail Detail : mesDetailList) {
                           for (MesMachinePaper mpaper : MPaper) {
                               if (mpaper.getPaperid().equals(Detail.getPaperid())) {
                                   BigDecimal total = Detail.getTotal();//退库数量
                                   BigDecimal number = mpaper.getNumber();//机台库存量
                                   if (number.compareTo(total) < 0) {
                                       throw new ServiceException("退库数量大于机台库存数量！");
                                   }
                               }
                           }
                       }
                   } else {
                       throw new ServiceException("机台库存没有数据");
                   }
                   for (MesRefundDetail Detail : mesDetailList) {
                       if (Info.getRefundMachineid() != null && Info.getRefundMachineid() != "" && Detail.getPaperid() != null) {
                           updateQuantity(Info.getRefundMachineid(), Detail.getPaperid(), Detail.getTotal());
                       }
                   }
               }
           }else{
          mesRefundInfoMapper.deleteMesRefundDetailByRefundid(mesRefundInfo.getId());
          insertMesRefundDetail(mesRefundInfo);
        }
        return mesRefundInfoMapper.updateMesRefundInfo(mesRefundInfo);
    }

    /**
     * 批量删除退库单
     * 
     * @param ids 需要删除的退库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesRefundInfoByIds(Long[] ids)
    {
        mesRefundInfoMapper.deleteMesRefundDetailByRefundids(ids);
        return mesRefundInfoMapper.deleteMesRefundInfoByIds(ids);
    }

    /**
     * 删除退库单信息
     * 
     * @param id 退库单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesRefundInfoById(Long id)
    {
        mesRefundInfoMapper.deleteMesRefundDetailByRefundid(id);
        return mesRefundInfoMapper.deleteMesRefundInfoById(id);
    }

    /**
     * 新增退库单明细信息
     * 
     * @param mesRefundInfo 退库单对象
     */
    public void insertMesRefundDetail(MesRefundInfo mesRefundInfo)
    {
        List<MesRefundDetail> mesRefundDetailList = mesRefundInfo.getMesRefundDetailList();
        Long id = mesRefundInfo.getId();
        if (StringUtils.isNotNull(mesRefundDetailList))
        {
            List<MesRefundDetail> list = new ArrayList<MesRefundDetail>();
            for (MesRefundDetail mesRefundDetail : mesRefundDetailList)
            {
                mesRefundDetail.setRefundid(id);
                list.add(mesRefundDetail);
            }
            if (list.size() > 0)
            {
                mesRefundInfoMapper.batchMesRefundDetail(list);
            }
        }
    }

    private void updateQuantity(String machineid, Long paperid, BigDecimal number){
        MesMachinePaper machinepaper=new MesMachinePaper();
        machinepaper.setMachineid(machineid);
        machinepaper.setPaperid(paperid);
        machinepaper.setNumber(number);
        machinepaper.setType((long) 2);
//        int id= mesPaperService.selectMachinePaper(machinepaper);//查询机台纸张
//        if (id>0){
            mesPaperService.updateMachinePaper(machinepaper);//修改机台纸张
//        }else{
//            mesPaperService.AddMachinePaper(machinepaper);//添加机台纸张
//        }
        MesPaper paper=new MesPaper();
        paper.setId(paperid);
        paper.setQuantity(number);
        paper.setQuantitymark(1);
        mesPaperService.updateMesPaperQuantity(paper);//加库存
    }



}
